new Vue({
    el: '#app',
    data() {
        return {
            pickerOptions: pickerOptions,
            form: {
                System_SerialNumber: '',
                System_Name: '',
                Picture_URL: '',
                System_Remark: '',
            },
            form1: [],
            fmfileList: [],
            loading: false,
            isEdit: true
        }
    },
    mounted() {
        const Enterprise_Info_SerialNumber = getCookie('enterprise')
        this.getData(Enterprise_Info_SerialNumber);
    },
    methods: {
        handleEdit() {
            if (!this.isEdit) {
                if (this.form.Enterprise_Info_SerialNumber != '5465465') {
                    this.form.Row_Status = '88';
                }
                this.loading = true;
                this.form.Children = {
                    enterprise_account: this.form1
                }
                const { add, modify } = this.deal();
                let data = {};
                if (add == null) {
                    data = {
                        Data: JSON.stringify({
                            Modify: { enterprise_info: [modify] },
                        }),
                    };
                } else {
                    data = {
                        Data: JSON.stringify({
                            Modify: { enterprise_info: [modify] },
                            Add: { enterprise_info: [add],},
                        }),
                    };
                }
                $.ajax({
                    headers: requestHeaders(),
                    type: "POST",
                    url: `${BASE_URL2}/generalBusiness/generalSave`,
                    data,
                    success: (Result) => {
                        this.isEdit = !this.isEdit;
                        if (this.form.Enterprise_Info_SerialNumber != '5465465') {
                            window.parent.document.location.href = '../../../login.html'
                        }
                    },
                    complete: (XMLHttpRequest) => {
                        this.loading = false
                    },
                    dataType: "json",
                });
            } else {
                if (this.form.Enterprise_Info_SerialNumber != '5465465') {
                    this.$confirm('此操作完成后将会对企业重新审核, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.isEdit = !this.isEdit;
                    }).catch(() => {
                    });
                } else {
                    this.isEdit = !this.isEdit;
                }   
            }
        },
        getData(Enterprise_Info_SerialNumber) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                type: "POST",
                data: {
                    Data: "enterprise_info",
                    Condition: "Enterprise_Info_SerialNumber='" + Enterprise_Info_SerialNumber + "'",
                },
                success: function (data) {
                    if (data.length == 1) {
                        console.log(data[0]);
                        that.form = data[0];
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                type: "POST",
                data: {
                    Data: "enterprise_account",
                    Condition: "Enterprise_Info_SerialNumber='" + Enterprise_Info_SerialNumber + "'",
                },
                success: function (data) {
                    // if (data.length == 1) {
                        that.form1 = data;
                    // }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
                },
                dataType: "json",
            });
        },
        handleRemove(file, fileList) {
            // this.fileList = [];
            this.fmfileList.splice(0, 1);
        },
        handleRemove1() {
            if (this['form1'].filter(item => item.Row_Status != '1').length > 1) {
                let i = this['form1'].filter(item => item.Row_Status != '1').length - 1
                let obj = this['form1'].filter(item => item.Row_Status != '1')[i]
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    this['form1'].pop();
                } else {
                    this.$confirm('该操作将删除此条数据,是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        this['form1'].filter(item => item.Row_Status != '1')[i].Row_Status = '1'
                    }).catch(() => {
                        this.$message({
                            type: 'warning',
                            message: '已取消删除'
                        });
                    });
                }
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        handleAdd() {
            this.form1.push({
                Enterprise_Info_SerialNumber: this.form.Enterprise_Info_SerialNumber,
                Bank_Name: '',
                Account_Number: '',
            })
        },
        submitForm(formName) {
            const that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.loading = true;
                    that.form.Children = {
                        enterprise_account: that.form1
                    }
                    const { add, modify } = that.deal();
                    let data = {};
                    if (add == null) {
                        data = {
                            Data: JSON.stringify({
                                Modify: { enterprise_info: [modify] },
                            }),
                        };
                    } else {
                        data = {
                            Data: JSON.stringify({
                                Modify: { enterprise_info: [modify] },
                                Add: { enterprise_info: [add],},
                            }),
                        };
                    }
                    $.ajax({
                        headers: requestHeaders(),
                        type: "POST",
                        // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                        url: `${BASE_URL2}/generalBusiness/generalSave`,
                        data,
                        success: function (Result) {
                            console.log(Result);
                            window.parent.document.location.href = 'login.html'
                        },
                        complete: function (XMLHttpRequest) {
                            //   requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json",
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        deal() {
            const add = deepClone(this.form);
            const modify = deepClone(this.form);
            let add_enterprise_account = [], modify_enterprise_account = [];
            for (const i in modify.Children.enterprise_account) {
                const obj = modify.Children.enterprise_account[i];
                if (!Object.keys(obj).some((item) => item.includes("_Original"))) {
                    add_enterprise_account.push(obj);
                } else {
                    modify_enterprise_account.push(obj);
                }
            }
            add.Children.enterprise_account = add_enterprise_account;
            modify.Children.enterprise_account = modify_enterprise_account;
            if (
                add_enterprise_account.length == 0
            ) {
                return { add: null, modify };
            }
            return { add, modify };
        },
        chandleChange(file, fileList) {
            // 这个方法现在主要用于调试或处理其他上传后的逻辑
            // 注意：这里的fileList参数与:file-list绑定的fileList不是同一个对象
            // :file-list绑定的fileList是组件内部维护的，而这里的fileList是上传事件提供的
            console.log("Upload change event:", file, fileList);
        },
        handleBeforeUpload(file) {
            const maxSize = 500 * 1024; // 500KB
            if (file.size > maxSize) {
                this.$message.error(
                    "图片大小超出限制，最大允许上传 500KB 的图片，请压缩后重新上传"
                );
                return;
            }
            // 生成预览URL并添加到fileList中
            const reader = new FileReader();
            reader.onload = (e) => {
                const newFile = {
                    name: file.name,
                    url: e.target.result, // 预览URL
                    uid: file.uid,
                    // 可以添加其他属性，如上传状态等
                };
                this.fmfileList.push(newFile);
                console.log(this.fmfileList);

                $.ajax({
                    // headers: requestHeaders(), // 确保这个函数返回正确的头部信息
                    url: "https://service.kdddy.cn/donghuiForRequest/store/photo",
                    // url: "http://192.168.10.79:8087/store/photo",
                    // url: "http://192.168.10.79:8087/store/photo",
                    type: "POST", // 注意HTTP方法应该大写
                    contentType: "application/json", // 设置请求体的媒体类型为application/json
                    data: JSON.stringify(this.fmfileList), // 将数据序列化为JSON字符串
                    success: function (Result) {
                        console.log(Result);
                    },
                    complete: function (XMLHttpRequest) {
                        requestPretreatment(XMLHttpRequest); // 确保这个函数在config/config.js中定义
                    },
                    dataType: "json", // 预期服务器返回的数据类型
                });
            };
            reader.readAsDataURL(file);
            // console.log(this.fmfileList);

            // 返回false以阻止自动上传
            return false;
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        uploadFront() {
            let _this = this
            let num = 1
            new Compressor(file, {
                quality: num,
                success(file) {
                    console.log(file.size)
                    const formData = new FormData();
                    formData.append('file', file, file.name);
                    let oFileReader = new FileReader();
                    oFileReader.readAsDataURL(file);
                    oFileReader.onload = function (e) {
                        $.ajax({
                            type: 'POST',
                            url: DomainName + '/FileList',
                            data: {
                                Data: e.target.result,
                                DataLength: file.size,
                                FileName: file.name,
                                Path: 'icon'
                            },
                            complete: function (XMLHttpRequest) {
                                _this.loading = false
                                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                                    window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                                }
                            },
                            success: function (Result) {
                                _this.form.pic = e.target.result
                                if (Result.Status == "success") {
                                    _this.form.Picture_URL = Result.Picture_Url
                                    _this.$message.success('上传成功')
                                } else {
                                    _this.$message.error('上传失败')
                                }
                            },
                            error: function () {
                                _this.$message.error("操作失败，请稍后再试")
                            },
                            dataType: "json"
                        });
                    }
                },
                error(err) {
                    console.log(err.message);
                },
            });
        }
    }
})